class EntryController < ApplicationController

  before_filter :find_account

  def new
    @entry = @account.entries.build(params[:entry])
    @entry.user = @user
    @entry.save
    @account.entries.apply_running_total

    render :update do |page|
      if @entry.new_record?
        page.replace_html 'entry-new', :partial => 'new'
      else
        page.replace_html 'ledger-body',
          :partial => 'entry',
          :collection => @account.entries
        page.replace_html 'balance', @account.balance.format
        page.replace_html 'entry-new', :partial => 'new'
        page.call "Ledger.load"
        page.visual_effect :highlight, "entry-#{@entry.id}"
        page.visual_effect :highlight, "balance"
      end
    end
  end

  def destroy
    @account.entries.find(params[:id]).destroy

    render :update do |page|
      page.visual_effect :fade, "entry-#{params[:id]}"
      page.remove "entry-#{params[:id]}"
      page.replace_html 'balance', @account.balance.format
      page.visual_effect :highlight, "balance"
    end
  end

  def auto_complete_payee
    payee_name = params[:entry][:payee_name].downcase

    find_options = {
      :conditions => [ "LOWER(payees.name) LIKE ?", payee_name + '%' ],
      :limit => 10,
      :order => "payees.name, entries.transaction_date",
      :group => "concat(payees.name, entries.category_id)"
    }

    @entries = @account.entries.find(:all, find_options)

    render :partial => "auto_complete_payee"
  end

  private

  def find_account
    @account = @user.accounts.find(params[:account])
  end

end
